package com.k2data.k2de.utils;

import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.message.MessageAndMetadata;
import kafka.serializer.Decoder;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by chen ming on 2017-12-19
 */
public class ConsumeKafkaTopicUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumeKafkaTopicUtil.class);

    public static List<KafkaStream<String, String>> getKafkaStreams(String topic, ConsumerConnector consumer) {

        //指定需要订阅的topic
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(topic, new Integer(1));

        //指定key的编码格式
        Decoder<String> keyDecoder = new StringDecoder(new VerifiableProperties());
        //指定value的编码格式
        Decoder<String> valueDecoder = new StringDecoder(new VerifiableProperties());

        //获取topic 和 接受到的stream 集合
        Map<String, List<KafkaStream<String, String>>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valueDecoder);

        //根据指定的topic 获取 stream 集合
        List<KafkaStream<String, String>> kafkaStreams = consumerMap.get(topic);

        return kafkaStreams;
    }

    public static Map<String, String> getKeyAndMsg(MessageAndMetadata<String, String> messageAndMetadata) throws Exception {

        String key;
        String msg;

        key = messageAndMetadata.key();
        msg = messageAndMetadata.message();
        if (null == msg) {
            LOGGER.error("Receive null message... ");
        }
        Map<String, String> map = new HashMap<>();
        map.put("key", key);
        map.put("msg", msg);

        return map;
    }
}